package pub.wkq.springbatch.batch._01_hello;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.JobFactory;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.batch.api.listener.JobListener;

/**
 * @author 21129
 */
@Component
@Configuration
public class HelloJob {
    // 作业启动器
    @Resource
    private JobLauncher jobLauncher;
    // Job 构建工厂  用于构建 Job 对象
    @Resource
    private JobBuilderFactory jobBuilderFactory;

    // Step 构建工厂 用于构建 Step 对象
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    // 构建一个 Step 对象执行的任务（逻辑对象）
    @Bean
    public Tasklet tasklet() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                System.out.println(" Hello World ");
                // 获取步骤状态
                System.out.println("stepContribution.getStepExecution().getStatus() = " + stepContribution.getStepExecution().getStatus());
                // 状态返回
                return RepeatStatus.FINISHED; // 执行完了
            }
        };
    }

    /**
     * 构建一个 Step 对象
     */
    @Bean
    public Step step1() {
        return stepBuilderFactory
                .get("step1") // 构建一个步骤，传入名称
                .tasklet(tasklet())// tasklet 执行 step 逻辑 类似 Thread()  可以执行 runnable 接口
                .build();
    }
    @Bean
    public JobExecutionListener jobStateListener() {
        return new JobStateListener();
    }
    /**
     *  构造出一个 Job 对象
     */
    @Bean
    public Job job() {
        return jobBuilderFactory
                .get("hello-job1")
                .start(step1())
                .listener(jobStateListener())
                .build();
    }
}
